import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_styled_toast/flutter_styled_toast.dart';
import 'package:hao_ke/consts/url_const.dart';
import 'package:hao_ke/utils/shared_preferences.dart';




class DioHttp {

  static final DioHttp _singleton = DioHttp._internal();
  factory DioHttp() => _singleton;
  DioHttp._internal();

  final BaseOptions options = BaseOptions(
    baseUrl: UrlConst.base,
    connectTimeout: Duration(seconds: 5),
    receiveTimeout: Duration(seconds: 3),
    headers: {
      'Content-Type': 'application/json',
    }
  );


  late Dio dio;
  late BuildContext context;
  late String authorization;

  late String token;

  DioHttp init(BuildContext context,String authorization) {
    this.context = context;
    options.headers['Authorization'] = authorization;
    dio = Dio(options);
    dio.interceptors.add(InterceptorsWrapper(
      onResponse: (response, handler) {
        if(response.statusCode==401) {
          Navigator.of(context).pushReplacementNamed('login');
        }
        return handler.next(response);
      },
      onError: (DioError e, handler) {
        print(e.response?.data);
        if (e.response?.statusCode == 401) {
          if(e.response?.data['error']=="unauthorized") {
            showToast("请先登录！",context:context,position: StyledToastPosition.center,backgroundColor: Colors.red[800]);
            Navigator.of(context).pushReplacementNamed('login');
            return;
          }
          Navigator.of(context).pushReplacementNamed('login');
          showToast("用户名或密码错误！",context:context,position: StyledToastPosition.center,backgroundColor: Colors.red[800]);
        }
        if (e.response?.statusCode == 403) {
          showToast("权限不足！",context:context,position: StyledToastPosition.center,backgroundColor: Colors.red[800]);
        }
        if (e.response?.statusCode == 404) {
          showToast("找不到页面，请联系管理员",context:context,position: StyledToastPosition.center,backgroundColor: Colors.red[800]);
        }
        if (e.response?.statusCode == 500) {
          showToast("操作错误",context:context,position: StyledToastPosition.center,backgroundColor: Colors.red[800]);
        }
        if(e.response?.statusCode == 400) {
          showToast(e.response?.data['error_description'],context:context,position: StyledToastPosition.center,backgroundColor: Colors.red[800]);
        }
        return handler.next(e);
      }
    ));
    this.authorization = authorization;
    return this;
  }

  static setAuthorization(String authorization) {
    _singleton.token = authorization;
  }

  // 生成get
  Future<dynamic> get(String url, {Map<String, dynamic>? params}) async {
    final response = await dio.get(url, queryParameters: params);
    return common(response);
  }

  // 生成post
  Future<dynamic> post(String url, {Map<String, dynamic>? params}) async {
    final response = await dio.post(url, queryParameters: params);
    return common(response);
  }

  // 生成put
  Future<dynamic> put(String url, {Map<String, dynamic>? params}) async {
    final response = await dio.put(url, data: params);
    return common(response);
  }

  // 生成delete
  Future<dynamic> delete(String url, {Map<String, dynamic>? params}) async {
    final response = await dio.delete(url, queryParameters: params);
    return common(response);
  }


  Object common(response) {
    if (response.statusCode==200) {
      return response.data;
    }else if(response.statusCode==401){
      Navigator.of(context).pushReplacementNamed('/login');
    }else if(response.statusCode==403){
      showToast("权限不足！",context:context,position: StyledToastPosition.center,backgroundColor: Colors.pink[300]);
      Navigator.of(context).pushReplacementNamed('/login');
    }else if(response.statusCode==500){
      showToast("服务器异常，请联系管理员",context:context,position: StyledToastPosition.center,backgroundColor: Colors.pink[300]);
    }else{
      showToast("服务器异常，请联系管理员",context:context,position: StyledToastPosition.center,backgroundColor: Colors.pink[300]);
    }
    return response.data;
  }



}

